<?php
/**
 * @author chenlisong E-mail:chenlisong1021@163.com 
 * @version 创建时间：2015年8月19日 上午11:20:31 
 * 类说明
 */
class BaseAction extends Action{
	
	public function _initialize() {
		header("Content-type: text/html; charset=utf-8");
		$this->theme('default');
		if (!isset($_SESSION['USER_ADMIN_KEY_ID'])) {
			$this->redirect('Admin/Login/login');
		}
		if (!isset($_SESSION['USER_ADMIN_KEY_GROUP_ID'])) {
			$this->redirect('Admin/Login/login');
		}else{
			if($_SESSION['USER_ADMIN_KEY_GROUP_ID']!=1){
				echo '<p style="text-align:center;margin-top: 50px;font-size: 25px;">无权限操作!</p>';
				exit;
			}
		}
		//获取网站头
		$this->assign('edu_title',getFields('title'));
		//获取菜单树
		import('ORG.Util.Auth');//加载类库
		$auth=new Auth();
		$uid = $_SESSION['USER_ADMIN_KEY_ID'];
		$this->uid = $uid;
		$menuList = $auth->getAuthMenuList($uid);
		if(isset($_SESSION['ADMIN_MENU_LIST'.$uid])){
			$mainMenu = $_SESSION['ADMIN_MENU_LIST'.$uid];
		}else{
			$menuList = $auth->getAuthMenuList($uid);
			//主菜单
			$i = 0;
			foreach($menuList as $key=>$val){
				if($val['parent_id'] == 0){
					$mainMenu[$i] = $menuList[$key];
					foreach($menuList as $key2=>$val2){
						if($val2['parent_id'] == $val['id']){
							$mainMenu[$i]['subMenu'][] = $val2;
						}
					}
					$i++;
				}
			}
			$_SESSION['ADMIN_MENU_LIST'.$uid] = $mainMenu;
		}
		$this->assign('menuList',$mainMenu);
		//超级管理员
		if(in_array(session('USER_ADMIN_KEY_ID'), C('ADMINISTRATOR'))){
			return true;
		}
		//过滤不需要验证的模块
		if(in_array(MODULE_NAME, C('NOT_AUTH_MODULE')) || in_array(ACTION_NAME, C('NOT_AUTH_ACTION'))){
			return true;
		}elseif(!$auth->check(GROUP_NAME . '/' . MODULE_NAME.'/index',session('USER_ADMIN_KEY_ID'))){
			echo '<p style="text-align:center;margin-top: 50px;font-size: 25px;">无权限操作!</p>';
			exit;
        }
	}
	
	/**
	 * @authority 新增
	 */
	public function add(){
		$this->display('add');
	}
	
	/**
	 * 插入
	 */
	public function insert(){
		$Model = M($this->getActionName());
		unset ( $_POST [$Model->getPk()] );
		if (false === $Model->create()) {
			$this->error($Model->getError());
		}
		//保存当前数据对象
		if ($result = $Model->add()) { //保存成功
			$this->ajaxReturn(1,L('ADMIN_ADD_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_ADD_ERROR'),0);
		}
	}
	
	/**
	 * @authority 修改
	 */
	public function edit() {
		$Model = M($this->getActionName());
		$map[$Model->getPk()] = $_REQUEST['id'];
		$vo = $Model->where($map)->find();
		$this->assign('vo',$vo);
		$this->display();
	}
	
	/**
	 * 更新
	 */
	public function update() {
		$Model = M($this->getActionName());
		if(false === $Model->create()) {
			$this->error($Model->getError());
		}
		// 更新数据
		if(false !== $Model->save()) {
			$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
		}
	}
	
	/**
	 * @authority 详细
	 */
	public function detailView() {
		$Model = M($this->getActionName());
		$map[$Model->getPk()] = $_REQUEST['id'];
		$vo = $Model->where($map)->find();
		$this->assign('vo',$vo);
		$this->display();
	}
	
	
	/**
	 * 逻辑删除
	 */
	public function logicDel(){
		$Model = M($this->getActionName());
		if (!empty($Model)) {
			$pk = $Model->getPk();
			$id = $_REQUEST[$pk];
			if (isset($id)) {
				$condition = array($pk => array('in', explode(',', $id)));
				if (false !== $Model->where($condition)->setField('flag',2)) {
					$this->ajaxReturn(1,L('ADMIN_DELETE_SUCCESS'),1);
				} else {
					$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
				}
			} else {
				$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
			}
		}
	}
	/**
	 * 物理删除
	 */
	public function del(){
		$Model = M($this->getActionName());
		if (!empty($Model)) {
			$pk = $Model->getPk();
			$id = $_REQUEST[$pk];
			if (isset($id)) {
				$condition = array($pk => array('in', explode(',', $id)));
				if (false !== $Model->where($condition)->delete()) {
					$this->ajaxReturn(1,L('ADMIN_DELETE_SUCCESS'),1);
				} else {
					$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
				}
			} else {
				$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
			}
		}
	}
	
	/**
	 * 更改状态
	 */
	public function updateStatus() {
		//删除指定记录
		$Model = M($this->getActionName());
		$pk = $Model->getPk();
		$id = $_REQUEST[$pk];
		if (isset($id)) {
			$condition = array($pk => array('in', explode(',', $id)));
			if (false !== $Model->where($condition)->setField($_REQUEST['field'],$_REQUEST['islock'])) {
				$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
			} else {
				$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
			}
		}
	}
	
	/**
	 * 封装dtgird的json数据
	 */
	public function toJosnForGird($data,$page){
		if(empty($page)){
			$page->page = 0;
			$page->total = 0;
			$page->records = 0;
		}
		$newdata['page'] = $page->page;
		$newdata['total'] = $page->total;
		$newdata['records'] = $page->records;
		$newdata['rows'] = $data;
		return $newdata;
	}
	
	public function pageParam($totalRows = 0){
		if(empty($totalRows)){
			return false;
		}
		$records = $totalRows;//总条数
		$listRows = empty($_GET['rows'])?20:$_GET['rows'];
		if(!empty($listRows)) {
			$listRows =   intval($listRows);
		}
		//排序
		$sidx = empty($_GET['sidx'])?M($this->getActionName())->getPk():$_GET['sidx'];
		$sord = empty($_GET['sord'])?"desc":$_GET['sord'];
		$sort = $sidx." ".$sord;
		$totalPages   =   ceil($totalRows/$listRows);     
		$nowPage      =   !empty($_GET['page'])?intval($_GET['page']):1;
		$firstRow     =   $listRows*($nowPage-1);
		$data['total'] = $totalPages; //总页数
		$data['page'] = $nowPage;//当前页数
		$data['records'] = $totalRows;//总数量
		$data['listRows'] = $listRows;//获取默认列表每页显示行数,默认20
		$data['firstRow'] = $firstRow;//当前页数-1
		$data['sort'] = $sort;
		return json_encode($data);
	}
	
	/**
	 * 领取自己的报单
	 */
	public function doneCustomLog($userId){
		$CustomsLog = M('CustomsLog');$User = M('User');$UserCostoms = M('UserCostoms');$UserDetails = M('UserDetails');
		$userInfo = $User->where('flag = 1 and id = '.$userId)->find();
		if(empty($userInfo)){
			return false;
		}
		//获取已经分润过的记录ID
		$ids = $UserCostoms->where('user_id = '.$userId)->getField('GROUP_CONCAT(customs_id)');
		$ids = explode(',', $ids);
		$ids = array_unique($ids);//数组去重
		$ids = implode(',', $ids);
		if(empty($ids)){
			$query = ' flag = 1 and FIND_IN_SET('.$userId.',for_user_id)';
		}else{
			$query = ' flag = 1 and id not in('.$ids.') and FIND_IN_SET('.$userId.',for_user_id)';
		}
		$data = $CustomsLog->where($query)->select();
		if(empty($data)){
			return false;
		}
		foreach ($data as $key=>$val){
			//领取权益
			$price = $val['price'] * $userInfo['beilv'];
			$ddata['user_id'] = $userId;
			$ddata['title'] = '分红奖励';
			$ddata['type'] = 1;
			$ddata['price'] = $price;
			$ddata['create_time'] = time();
			$UserDetails->add($ddata);
			$fdata['intg'] = array('exp','intg + '.$price);
			$User->where('flag = 1 and id = '.$userId)->save($fdata);
			//记录已领取过
			$ucdata['user_id'] = $userId;
			$ucdata['customs_id'] = $val['id'];
			$UserCostoms->add($ucdata);
		}
	}
	
	/**
	 * 计算自己的业绩
	 * 3级代理商（总营业额300万，其中两条线的营业额>50%，且直推三个人），2级（3000万），1级（9000万）
	 */
	public function computeSorce($userId){
		$User = M('User');$Score = M('Score');
		$userInfo = $User->where('flag = 1 and id = '.$userId)->find();
		if(empty($userInfo)){
			return false;
		}
		$scoreInfo = $Score->where('flag = 1 and user_id = '.$userId)->find();
		$where['flag'] = 1;
		$where['isvip'] = 1;
		$timeStarp = intval($scoreInfo['update_time']);
		$where['vip_time'] = array('gt',$timeStarp);
		if(empty($userInfo['is_A'])){
			$scoreA = 0;
		}else{
			$where['id'] = $userInfo['is_A'];
			$count = $User->where($where)->count();
			if($count){
				$value = $scoreInfo['score_A'] + 398;
			}else{
				$value = floatval($scoreInfo['score_A']);
			}
			$scoreA = $this->addSorce($userInfo['is_A'],$value,$timeStarp);
		}
		if(empty($userInfo['is_B'])){
			$scoreB = 0;
		}else{
			$where['id'] = $userInfo['is_B'];
			$count = $User->where($where)->count();
			if($count){
				$value = $scoreInfo['score_B'] + 398;
			}else{
				$value = floatval($scoreInfo['score_B']);
			}
			$scoreB = $this->addSorce($userInfo['is_B'],$value,$timeStarp);
		}
		if(empty($userInfo['is_C'])){
			$scoreC = 0;
		}else{
			$where['id'] = $userInfo['is_C'];
			$count = $User->where($where)->count();
			if($count){
				$value = $scoreInfo['score_C'] + 398;
			}else{
				$value = floatval($scoreInfo['score_C']);
			}
			$scoreC = $this->addSorce($userInfo['is_C'],$value,$timeStarp);
		}
		$data['score_A'] = $scoreA;
		$data['score_B'] = $scoreB;
		$data['score_C'] = $scoreC;
		$data['user_id'] = $userId;
		$data['update_time'] = time();
		//判断自己是否达到代理商级别
		if($userInfo['level'] == 0){
			$mubiao = 3000000;$level = 3;
		}elseif($userInfo['level'] == 3){
			$mubiao = 30000000;$level = 2;
		}elseif($userInfo['level'] == 2){
			$mubiao = 90000000;$level = 1;
		}
		if($userInfo['beilv'] >= 5 && !empty($level) && !empty($mubiao)){
			if(($scoreA + $scoreB + $scoreC) > $mubiao){
				if(($scoreA + $scoreB) > $mubiao*0.5 || ($scoreA + $scoreC) > $mubiao*0.5 || ($scoreC + $scoreB) > $mubiao*0.5){
					$User->where('flag = 1 and id = '.$userId)->setField('level', $level);
				}
			}
		}
		//统计业绩
		if(empty($scoreInfo)){
			$data['create_time'] = time();
			$Score->add($data);
		}else{
			$Score->where('flag = 1 and user_id = '.$userId)->save($data);
		}
	}
	
	/**
	 * 计算自己的业绩
	 * @param unknown $userId
	 */
	public function addSorce($userIds,$value,$timeStrap){
		$User = M('User');
		$where['flag'] = 1;
		$where['isvip'] = 1;
		$where['place_id'] = array('in',$userIds);
		$data = $User->where($where)->field('id,vip_time')->select();
		if(!empty($data)){
			//已经统计过的要剔除
			$newData = array();
			foreach ($data as $key=>$val){
				if($val['vip_time'] > $timeStrap){
					$newData[] = $val;
				}
				$ids[$key] = $val['id'];
			}
			$ids = implode(',',$ids);
			$nums = count($newData);
			$value += $nums * 398;
			return $this->addSorce($ids,$value,$timeStrap);
		}else{
			return $value;
		}
	}
}